package feeinterface.protocol.req;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.ulwx.tool.CTime;
import com.ulwx.tool.StringUtils;
import com.ulwx.type.TString;

import feeinterface.dao.BaseDynamicQuestionAnswerDao;
import feeinterface.dao.BaseDynamicQuestionAnswerForEditDao;
import feeinterface.dao.BaseDynamicRegularDao;
import feeinterface.dao.ChannelDynamicValidateRecordDao;
import feeinterface.modeldb.BaseDynamicQuestionAnswer;
import feeinterface.modeldb.BaseDynamicQuestionAnswerForEdit;
import feeinterface.modeldb.BaseDynamicRegular;
import feeinterface.modeldb.ChannelDynamicValidateRecord;
import feeinterface.protocol.business.ParseFetch;
import feeinterface.protocol.res.Res010002;
import feeinterface.protocol.utils.Constants;

/**
 * 动态验证码响应
 * 
 * @author 黄杰
 * 
 */
public class Pro010002 extends ProExchange {
	/**
	 * 日志
	 */
	private static Logger log = Logger.getLogger(Pro010002.class); // 跟类名一样

	@Override
	@SuppressWarnings("all")
	public Object genBean() throws Exception {
		// 根据获得的参数，进行相关的操作，例如查询数据库，最后把数据塞入到协议类
		// 调用协议类
		Res010002 res = new Res010002();
		try {
			// 去除短信中(2/2)或者(3/3)等短信内容
			this.Content = this.Content.replaceAll(
					"[\\(（] *\\d+ */ *\\d+ *[\\)）]", "");

			// 动态验证请求记录
			ChannelDynamicValidateRecord record = new ChannelDynamicValidateRecord();
			res.ValidateCode = "";
			String fetchQuestion = "";// 抓取动态问题
			/**
			 * 第一个：省份id 第二个：城市id
			 */
			int areaId[] = this.getAreaID(IMSI, SmsCenter);
			TString carrier = new TString("移动");
			int[] areaIDs = this.getAreaID("", IMSI, this.SmsCenter, carrier);
			// 步骤一：根据通道ID和省份ID获取动态验证规则
			List<BaseDynamicRegular> cregulars = null;
			try {
				// 更改：孙超进 2012-03-14
				cregulars = BaseDynamicRegularDao.getDyRegularBy(areaId[0],
						this.ChannelID, carrier.getValue());

				if (cregulars != null && cregulars.size() > 0) {

					for (int i = 0; i < cregulars.size(); i++) {
						BaseDynamicRegular cregular = cregulars.get(i);
						String regexRegular = cregular.getRegexRegular();
						// 如果是含有正则表达式，表明送上来的是规则动态（可能是客户端有bug）。大部分情况下，客户端送上来的是
						// 不规则的。如果没有配置正则表达式，表明送上来的是不规则动态
						if (StringUtils.hasText(regexRegular)
								&& regexRegular.length() > 1) {

							fetchQuestion = getValidateCode(Content,
									regexRegular);
							if (StringUtils.hasText(fetchQuestion)) {
								break;
							}

						}
					}

					if (StringUtils.hasText(fetchQuestion)) {// 规则动态处理
						res.ValidateCode = fetchQuestion;
					} else {// 表明要通过不规则动态验证处理
						for (int i = 0; i < cregulars.size(); i++) {
							BaseDynamicRegular cregular = cregulars.get(i);
							if (StringUtils.hasText(cregular.getStartFlag())
									|| StringUtils.hasText(cregular
											.getEndFlag())) {

								fetchQuestion = ParseFetch.StringIntercept(
										Content, cregular.getStartFlag(),
										cregular.getEndFlag());
								if (fetchQuestion.length() == Content.length()) {
									continue;
								}

								// 步骤二： 根据验证短信内容提取动态验证码
								if (StringUtils.hasText(fetchQuestion)) {
									try {

										record.setProvinceID(cregular
												.getProvinceID());
										log.debug("根据省份ID和通道ID提取动态验证码！"
												+ res.ValidateCode);

										BaseDynamicQuestionAnswer answer = BaseDynamicQuestionAnswerDao
												.getAnswerByQuestion(fetchQuestion);
										if (null != answer) {
											res.ValidateCode = StringUtils
													.trim(answer.getAnswer());
										} else {// 收集问题
											res.ValidateCode = "";
											if (!"".equals(StringUtils
													.trim(fetchQuestion))) {
												log.info("抓取的问题:"
														+ fetchQuestion);
												BaseDynamicQuestionAnswerForEdit ans = new BaseDynamicQuestionAnswerForEdit();
												ans.setProvinceID(areaId[0]);
												ans.setQuestion(fetchQuestion);
												ans.setAddTime(CTime
														.getCurrentDateTime());
												BaseDynamicQuestionAnswerForEditDao
														.InsertData(ans);
											}
										}
										

									} catch (Exception e) {
										log.error("根据验证短信内容提取动态验证码失败！", e);
										// throw new
										// ExchangeException(Constants.Status.FAIL,
										// "根据验证短信内容提取动态验证码失败！");
									}
									
									break;
								}
							}

						}// /
					}

				} else {
					throw new ExchangeException(Constants.Status.FAIL,
							"未找到动态验证规则！");
				}
			} catch (Exception e) {
				log.error("获取动态验证规则失败！", e);
				// throw new ExchangeException(Constants.Status.FAIL,
				// "获取动态验证规则失败！");
			}

			// 带验证信息的短信内容
			record.setChannelID(this.ChannelID);
			record.setDestAddr(this.DestAddr);
			record.setContent(Content);
			record.setAddTime(CTime.getCurrentDateTime());
			record.setIMSI(IMSI);
			record.setValidateCode(res.ValidateCode);
			// 保存记录
			ChannelDynamicValidateRecordDao.addChannelValidateRecord(record);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			// throw new ExchangeException(Constants.Status.FAIL,
			// e.getMessage());
		}
		if (!"".equals(res.ValidateCode)) {
			// 赋固定值
			res.Status = Constants.Status.SUCCESS;
			res.Message = "成功";
		} else {
			// 赋固定值
			res.Status = Constants.Status.FAIL;
			res.Message = "失败";
		}
		res.DestAddr = DestAddr;
		return res;
	}

	/**
	 * 提取动态验证码
	 * 
	 * @param content
	 * @param regular
	 * @return
	 */
	public static String getValidateCode(String content, String regular) {
		// 提取动态验证码
		// 如，Content=感谢使用，本次密码123434，中国移动,而regular="本次密码(.*)，",则验证码为：123434
		String validateCode = "";
		Pattern p = null;
		Matcher m = null;
		p = Pattern.compile(regular);
		m = p.matcher(content);
		if (m.find()) {
			validateCode = m.group(1);
		}
		return validateCode;
	}

	@Override
	public String validate() throws Exception {

		if (StringUtils.isEmpty(Content))
			return "失败";

		return null;
	}

	/**
	 * 付费记录编号，32位随机编号
	 */
	public String FeeID;
	/**
	 * 包id
	 */
	public String PacketID;
	/**
	 * 付费类型
	 */
	public Integer FeeType;
	/**
	 * 通道ID
	 */
	public Integer ChannelID;
	/**
	 * 版本号id，函数库的版本号
	 */
	public Integer Ver;
	/**
	 * 虚拟机版本号
	 */
	public Integer VmVer;
	/**
	 * 平台简称
	 */
	public String Platform;
	/**
	 * 短信中心号码，允许为空
	 */
	public String SmsCenter;
	/**
	 * 手机卡串号
	 */
	public String IMSI;
	/**
	 * 合作业务ID，后台通过此id可以找到对应的产品， 产品的概念：好玩吧 ，哈密瓜等
	 */
	public Integer COID;
	/**
	 * 端口号码
	 */
	public String DestAddr;
	/**
	 * 包含验证码的验证短信内容。
	 */
	public String Content;

	/**
	 * 无参构造函数
	 */
	public Pro010002() {
		this.Protocol = "010002";
	}

	public static void main(String[] args) {
		System.out.println("dddd(6 /     2）,,(3/4)".replaceAll(
				"[\\(（] *\\d+ */ *\\d+ *[\\)）]", ""));
	}

}
